import { Image, List, InfiniteScroll } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { fetchListAPI, type ListRes } from '../../../apis/list'
import { useNavigate } from 'react-router-dom'

// 父组件传递过来的参数
type Props = {
  channelId: string
}

const HomeList = (props: Props) => {
  const { channelId } = props

  // list control
  const [listRes, setListRes] = useState<ListRes>({
    results: [],
    pre_timestamp: '' + new Date().getTime(),
  })

  // 初始数据获取
  useEffect(() => {
    const getList = async () =>  {
      try {
        const res = await fetchListAPI({
          channel_id: channelId,
          timestamp: '' + new Date().getTime(),
        })
        setListRes({
          results: res.data.data.results,
          pre_timestamp: res.data.data.pre_timestamp
        })
      } catch (error) {
        console.log(error)
      }
    }
    getList()
  }, [channelId])

  // 加载更多
  // 开关，标记当前是否还有新数据
  // 上拉加载触发的必要条件：1、hasMore = true  2、小于threshold
  const [hasMore, setHasMore] = useState(true)
  const loadMore = async () => {
    // 编写加载下一页的核心逻辑
    try {
      const res = await fetchListAPI({
        channel_id: channelId,
        timestamp: listRes.pre_timestamp,
      })
      // 没有数据立刻停止监听
      if (res.data.data.results.length === 0) {
        setHasMore(false)
      }
      setListRes({
        // 拼接新老列表数据
        results: [...listRes.results, ...res.data.data.results],
        // 重置时间参数 为下一次请求做准备
        pre_timestamp: res.data.data.pre_timestamp,
      })
    } catch (error) {
      console.log(error)
    }
  }

  const navicate = useNavigate()
  const goToDetail = (id: string) => {
    // 路由跳转
    navicate(`/detail?id=${id}`)
  }

  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item
          onClick={() => goToDetail(item.art_id)}
            key={item.art_id}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            description={item.pubdate}
            >
            {item.title}
          </List.Item>
        ))}
      </List>

      {/* loadMore：当滚动到页面底部时，触发的函数，加载数据 */}
      {/* hasMore：开关，告诉是否还有可加载的数据，如果传过来false表明没有更多数据了，停止继续加载 */}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10}/>
    </>
  )
}

export default HomeList